package com.jiepos.mpos.biz.appInfM.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.DBConstant;
import com.jiepos.mpos.common.constant.DBConstant.Table;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.MessageInfDao;
import com.jiepos.mpos.common.entity.App_Custom_InfEntity;
import com.jiepos.mpos.common.entity.App_Ins_InfEntity;
import com.jiepos.mpos.common.entity.App_Message_InfEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.CollectionUtil;
import com.jiepos.mpos.core.util.IDFactoryUtil;
import com.jiepos.mpos.core.util.StringUtils;
import com.jiepos.mpos.inter.push.MposPush;
import com.jiepos.mpos.inter.push.jiguang.JGPushService;

/**
 *
 *
 * <p>标题: —— 客户端推送消息类</p>
 * <p>模块: 通用平台</p>
 * <p>版权: Copyright (c) 2017 江苏杰博实信息技术有限公司
 * @ProjectName:  [mpos]
 * @Package com.jiepos.mpos.biz.appInfM.service
 * @author 余翼膑
 * @version 1.0
 * @since 2017年9月22号
 * @history（历次修订内容、修订人、修订时间等）
 */
@Service
public class MessageInfService extends BaseService {
    @Autowired
    private MessageInfDao messageInfDao;
    @Autowired
    private JGPushService jgPushService;
    @Autowired
    private CustomMsgService customMsgService;

    /**
     * 查询通知公告信息列表json分页数据
     *
     * @param pagination
     * @param appMessageInfEntity
     * @return
     */
    public Map getNoticeList(HttpServletRequest request, Pagination pagination, App_Message_InfEntity appMessageInfEntity, App_Ins_InfEntity appInsInfEntity) {
        StringBuffer sb = getInitSql("t1").append(",");
        sb.append(" T1.MESSAGE_UUID AS UUID,T1.MESSAGE_TITLE,T1.MESSAGE_TYPE,T2.INS_CD||'-'||T2.INS_CN_NM AS INST_NAME,T1.REC_ID, T1.MESSAGE_CONTENT,")
                .append("  T1.PUBLISH_ST||'-' || T3.CODE_DESC as PUBLISH_ST ")
                .append(" FROM ")
                .append(DBConstant.Table.T_APP_MESSAGE_INF)
                .append(" T1 LEFT JOIN ")
                .append(DBConstant.Table.T_APP_INS_INF)
                .append(" T2 ON T1.INS_UUID = T2.INS_UUID ")
                .append("  LEFT JOIN T_APP_CODE_LIST T3  ON T1.PUBLISH_ST = t3.code_val and t3.code_tp='PUBLISH_ST' ")
                .append(" where 1 = 1 ");
        List list = new ArrayList();
        //标题
        if (!StringUtils.isBlank(appMessageInfEntity.getMessage_title())) {
            sb.append(" AND T1.MESSAGE_TITLE LIKE ? ");
            list.add("%" + appMessageInfEntity.getMessage_title() + "%");
        }
        //发布状态
        if (!StringUtils.isBlank(appMessageInfEntity.getPublish_st())) {
            sb.append(" AND T1.PUBLISH_ST LIKE ? ");
            list.add("%" + appMessageInfEntity.getPublish_st() + "%");
        }
        //机构名称
        if (!StringUtils.isBlank(appInsInfEntity.getIns_cn_nm())) {
            sb.append(" AND T2.ins_cn_nm LIKE ? ");
            list.add("%" + appInsInfEntity.getIns_cn_nm() + "%");
        }
        pagination.queryString = sb.toString();
        pagination = getInsAuthSql(request, pagination, "T1", null);
        pagination = this.getOrderSql(pagination, "T1");
        return messageInfDao.getPaginationMap(pagination, "T1", list);
    }

    /**
     * 根据记录id查询实体对象
     *
     * @param message_uuid
     * @return
     */
    public Map getNoticeById(String message_uuid) {
        if (StringUtils.isBlank(message_uuid) || message_uuid.equals("undefined")) {
            return new HashMap();
        }
        StringBuilder sb = new StringBuilder();
        sb.append(" SELECT T1.MESSAGE_UUID,T1.INS_UUID,T1.CUSTOM_UUID,T1.MESSAGE_TITLE,T1.MESSAGE_CONTENT,T1.MESSAGE_ST,T1.MESSAGE_TYPE,T1.SEND_TYPE,T1.REC_ID,T1.PUBLISH_ST ")
                .append(",T2.INS_CD||'-'||T2.INS_CN_NM  AS INST_NAME ")
                .append(" FROM  ")
                .append(DBConstant.Table.T_APP_MESSAGE_INF)
                .append(" T1 LEFT JOIN ")
                .append(DBConstant.Table.T_APP_INS_INF)
                .append(" T2 ON T1.INS_UUID = T2.INS_UUID ")
                .append(" WHERE T1.message_uuid = ?");
        List<String> list = new ArrayList<>();
        list.add(message_uuid);
        List<Map<String, Object>> results = messageInfDao.queryForList(getOrderSql(sb.toString(), "t1"), list);
        return results != null ? results.get(0) : new HashMap<String, Object>();

    }

    /**
     * 保存通知公告
     *
     * @param appMessageInfEntity
     * @param map
     */
    public void saveNotice(App_Message_InfEntity appMessageInfEntity, Map map) {
        //当前用户
        appMessageInfEntity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
        if (org.apache.commons.lang.StringUtils.isBlank(appMessageInfEntity.getIns_uuid())) {
            appMessageInfEntity.setIns_uuid(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_INS_UUID)));
        }
        if (!StringUtils.isBlank(appMessageInfEntity.getMessage_uuid())){
        	App_Message_InfEntity oldMessage = getNoticeEntityByUUID(appMessageInfEntity.getMessage_uuid());
        	oldMessage.setIns_uuid(appMessageInfEntity.getIns_uuid());
        	oldMessage.setMessage_title(appMessageInfEntity.getMessage_title());
        	oldMessage.setMessage_content(appMessageInfEntity.getMessage_content());
        	oldMessage.setLast_oper_in(SystemConstant.OPER_UPDATE);
        	oldMessage.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
            List noChangeList = new ArrayList();
            noChangeList.add("message_uuid");
            noChangeList.add("rec_crt_ts");
            messageInfDao.update(oldMessage, noChangeList);
        } else {
           /* this.pushMessage(null ,appMessageInfEntity.getIns_uuid(), appMessageInfEntity.getMessage_title(), appMessageInfEntity.getMessage_content(),appMessageInfEntity.getRec_upd_usr_id());*/
            appMessageInfEntity.setMessage_uuid(IDFactoryUtil.getUUID());
            appMessageInfEntity.setMessage_st(SystemConstant.MESSAGE_ST_1);
            /*appMessageInfEntity.setRec_crt_ts(new Timestamp(System.currentTimeMillis()));
            appMessageInfEntity.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
            appMessageInfEntity.setRec_st(SystemConstant.REC_ST_1);// 正常状态*/
          /*  appMessageInfEntity.setLast_oper_in(SystemConstant.OPER_ADD);// 新增记录*/
            appMessageInfEntity.setPublish_st(SystemConstant.PUBLISH_ST);// 已发布状态
            appMessageInfEntity.setSend_type(SystemConstant.SEND_TYPE_1);// 发送类型通知公告
            appMessageInfEntity.setMessage_type(SystemConstant.MESSAGE_TYPE_PUBLIC);// 公有消息
            appMessageInfEntity = (App_Message_InfEntity) this.saveCommonData(appMessageInfEntity, map, "null");
            messageInfDao.save(appMessageInfEntity);
    }

    }

    /**
     * 查询私有推送信息列表json分页数据
     *
     * @param pagination
     * @param appMessageInfEntity
     * @return
     */
    public Map getPushMessageList(HttpServletRequest request, Pagination pagination, App_Message_InfEntity appMessageInfEntity, App_Custom_InfEntity appCustomInfEntity) {
        String ins_phone = String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_INS_PHONE));
        StringBuffer sb = getInitSql("t1").append(",");
        sb.append(" T1.MESSAGE_UUID AS UUID,T1.MESSAGE_TITLE,T1.MESSAGE_TYPE,T1.REC_ID, T1.MESSAGE_CONTENT,")
                .append(" NVL2(T3.INS_CD||T3.INS_CN_NM,T3.INS_CD || '-' || T3.INS_CN_NM  ,'') as NAME , ")
                .append(" CONCAT (RPAD (SUBSTR (T2.login_id, 1, 3),LENGTH (T2.login_id) - 4,'*'),SUBSTR (T2.login_id,LENGTH (T2.login_id) - 3,4)) || NVL2(T2.name, '-'||T2.name, '') as CUSTOM_NAME ")
                .append(" FROM ")
                .append(DBConstant.Table.T_APP_MESSAGE_INF)
                .append(" T1  LEFT JOIN "+Table.T_APP_CUSTOM_INF+" T2  ON T1.CUSTOM_UUID =T2.CUSTOM_UUID ")
                .append("  LEFT JOIN "+Table.T_APP_INS_INF+" T3 ON T1.INS_UUID = T3.INS_UUID ")
                .append(" where 1 = 1 ");
        List list = new ArrayList();
        //标题
        if (!StringUtils.isBlank(appMessageInfEntity.getMessage_title())) {
            sb.append(" AND T1.MESSAGE_TITLE LIKE ? ");
            list.add("%" + appMessageInfEntity.getMessage_title() + "%");
        }
        //会员登陆账号
        if (!StringUtils.isBlank(appCustomInfEntity.getLogin_id())) {
            sb.append(" AND T2.LOGIN_ID LIKE ? ");
            list.add("%" + appCustomInfEntity.getLogin_id() + "%");
        }
        //会员名称
        if (!StringUtils.isBlank(appCustomInfEntity.getName())) {
            sb.append(" AND T2.NAME LIKE ? ");
            list.add("%" + appCustomInfEntity.getName() + "%");
        }
        pagination = getInsAuthSql(request, pagination, "T1", null);
        sb.append(" OR  T1.CUSTOM_UUID in ");
        sb.append(" (select t.CUSTOM_UUID from "+Table.T_APP_CUSTOM_INF+" t ");
        sb.append(" start with t.CUSTOM_UUID= (SELECT CUSTOM_UUID\n" +
                "                       FROM T_APP_CUSTOM_INF\n" +
                "                      WHERE PHONE = '"+ins_phone+"')");
        sb.append(" connect by prior t.CUSTOM_UUID = t.SUP_CUSTOM_UUID)");
        pagination.queryString = sb.toString();
        // 如果是机构信息，则查询机构表
        // 如果此用户是属于某个机构，则获取当前机构及下级机构代码
        pagination = this.getOrderSql(pagination, "T1");
        return messageInfDao.getPaginationMap(pagination, "T1", list);
    }

    /**
     * 保存消息推送
     *
     * @param appMessageInfEntity
     * @param map
     */
    public void savePushMessage(App_Message_InfEntity appMessageInfEntity, Map map,String custom_uuid,String ins_uuid) {
        //判断是否存在机构uuid
        if(StringUtils.isEmpty(ins_uuid)){
            ins_uuid =null;
        }
        //判断是否存在clientid
        String clientid = null;
        if(!StringUtils.isEmpty(custom_uuid)){
            Map getClientid = this.getClientid(custom_uuid);
            if(CollectionUtil.isEmpty(getClientid)){
            }
            clientid = String.valueOf(getClientid.get("getui_clientid"));
        }
        //当前用户
        appMessageInfEntity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
        if (org.apache.commons.lang.StringUtils.isBlank(appMessageInfEntity.getIns_uuid())) {
            appMessageInfEntity.setIns_uuid(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_INS_UUID)));
        }
        if (!StringUtils.isBlank(appMessageInfEntity.getMessage_uuid())) {
            appMessageInfEntity = (App_Message_InfEntity) this.saveCommonData(appMessageInfEntity, map, "update");
            List noChangeList = new ArrayList();
            noChangeList.add("ins_app_uuid");
            noChangeList.add("rec_crt_ts");
            messageInfDao.update(appMessageInfEntity, noChangeList);
        } else {
            this.pushMessage(custom_uuid ,ins_uuid, appMessageInfEntity.getMessage_title(), appMessageInfEntity.getMessage_content(),appMessageInfEntity.getRec_upd_usr_id());
        }
    }

    /**
     * 获取用户的Clientid
     * @param custom_uuid
     * @return
     */
    public Map getClientid(String custom_uuid){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT T.GETUI_CLIENTID FROM ")
                .append(" T_APP_CUSTOM_INF T WHERE T.CUSTOM_UUID = ? ");
        List prarm = new ArrayList();
        prarm.add(custom_uuid);
        List<Map<String, Object>> resultList = messageInfDao.queryForList(sqlBuf.toString(), prarm);
        return resultList != null ? resultList.get(0) : new HashMap<String, Object>();
    }

    /**
     * 根据记录id查询实体对象
     *
     * @param message_uuid
     * @return
     */
    public Map getPushMessageById(String message_uuid) {
        if (StringUtils.isBlank(message_uuid) || message_uuid.equals("undefined")) {
            return new HashMap();
        }
        StringBuilder sb = new StringBuilder();
        sb.append(" SELECT T1.MESSAGE_UUID,T1.INS_UUID,T1.CUSTOM_UUID,T1.MESSAGE_TITLE,T1.MESSAGE_CONTENT,T1.MESSAGE_ST,T1.MESSAGE_TYPE,T1.SEND_TYPE,T1.REC_ID,T1.PUBLISH_ST, ")
                .append(" T2.LOGIN_ID, T2.LOGIN_ID||'-'|| T2.NAME as CUSTOM_NAME, ")
                .append(" T3.INS_CD||'-'||T3.INS_CN_NM AS NAME  ")
                .append(" FROM  ")
                .append(DBConstant.Table.T_APP_MESSAGE_INF)
                .append(" T1  LEFT JOIN T_APP_CUSTOM_INF T2  ON T1.CUSTOM_UUID =T2.CUSTOM_UUID ")
                .append(" LEFT JOIN "+Table.T_APP_INS_INF+" T3 ON T1.INS_UUID = T3.INS_UUID ")
                .append(" WHERE T1.message_uuid = ?");
        List<String> list = new ArrayList<>();
        list.add(message_uuid);
        List<Map<String, Object>> results = messageInfDao.queryForList(getOrderSql(sb.toString(), "t1"), list);
        return results != null ? results.get(0) : new HashMap<String, Object>();
    }

    /**
     * 发布和取消发布
     * @param message_uuids
     * @param publish_st
     * @param loginUser
     */
    public void updNoticeDetail(String message_uuids, String publish_st, Map loginUser) {
        messageInfDao.updateByIds("message_uuid", message_uuids, publish_st,String.valueOf(loginUser.get(SystemConstant.SESSION_LOGIN_USER)));
    }

//    /**
//     * 根据会员UUID得到推送消息集合(所有) For App
//     * @param custom_uuid
//     * @return
//     */
//    public List<Map<String,Object>> getNoticeList(String custom_uuid){
//        StringBuffer sqlBuf = new StringBuffer();
//        sqlBuf.append(" SELECT A.MESSAGE_TITLE as \"message_title\", A.REC_CRT_TS as \"rec_crt_ts\", B.READ_ST as \"read_st\" ")
//                .append("  FROM (SELECT MESSAGE_UUID, ")
//                .append("                     MESSAGE_TITLE, ")
//                .append("                     TO_CHAR(REC_CRT_TS, 'yyyy-mm-dd hh24:mi:ss') REC_CRT_TS ")
//                .append("                FROM T_APP_MESSAGE_INF ")
//                .append("               WHERE CUSTOM_UUID = ? ")
//                .append("                 AND REC_ST != '0' ")
//                .append("                 AND SEND_TYPE = '"+SystemConstant.SEND_TYPE_1+"' ")
//                .append("                 AND MESSAGE_ST = '"+SystemConstant.MESSAGE_ST_1+"') A ")
//                .append("   JOIN (SELECT MESSAGE_UUID, READ_ST ")
//                .append("           FROM T_APP_CUSTOM_MSG ")
//                .append("          WHERE CUSTOM_UUID = ? AND READ_ST = '"+SystemConstant.READ_ST_0+"') B ")
//                .append("     ON A.MESSAGE_UUID = B.MESSAGE_UUID ");
//        List<String> params = new ArrayList<>();
//        params.add(custom_uuid);
//        params.add(custom_uuid);
//        return messageInfDao.queryForList(sqlBuf.toString(),params);
//    }

    /**
     * 得到未读通知公告数量
     * @param ins_uuid 机构uuid
     * @param custom_uuid 会员uuid
     * @return
     */
    public String getUnReadNoticeCount(String ins_uuid,String custom_uuid,Timestamp custom_crt_ts){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT COUNT(MESSAGE_UUID) AS COUN ")
                .append("           FROM  "+ DBConstant.Table.T_APP_MESSAGE_INF)
                .append("          WHERE INS_UUID = ? ")
                .append("            AND REC_ST != '0' ")
                .append("            AND SEND_TYPE = '"+SystemConstant.SEND_TYPE_1+"' ")
                .append("            AND PUBLISH_ST = '"+SystemConstant.PUBLISH_ST+"' ")
                .append("            AND REC_UPD_TS > ? ")
                .append("            and MESSAGE_UUID not in ")
                .append("                (SELECT MESSAGE_UUID ")
                .append("                   FROM  "+ DBConstant.Table.T_APP_CUSTOM_MSG)
                .append("                  WHERE CUSTOM_UUID = ? ")
                .append("                    and READ_ST = '"+SystemConstant.READ_ST_1+"') ")
                .append("          order by REC_UPD_TS desc ");
        List<Object> params = new ArrayList<>();
        params.add(ins_uuid);
        params.add(custom_crt_ts);
        params.add(custom_uuid);
        List<Map<String,Object>> list = messageInfDao.queryForList(sqlBuf.toString(), params);
        if(list != null && list.size()>0 && list.get(0)!=null && list.get(0).get("COUN") !=null){
            return String.valueOf(list.get(0).get("COUN"));
        }else{
            return "0";
        }

    }

    /**
     * 根据会员UUID得到通知公告（1条） For App
     * @param ins_uuid 机构uuid
     * @param custom_uuid 会员uuid
     * @return
     */
    public List<Map<String,Object>> getNoticeList(String ins_uuid,String custom_uuid,Timestamp custom_crt_ts){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT A.MESSAGE_TITLE as \"message_title\", ")
                .append("        A.REC_CRT_TS as \"rec_crt_ts\", ")
                .append("        A.MESSAGE_UUID as \"message_uuid\", ")
                .append("        A.MESSAGE_CONTENT as \"message_content\", ")
                .append("        '"+SystemConstant.READ_ST_0+"' as \"read_st\" ")
                .append("   FROM (SELECT MESSAGE_UUID, ")
                .append("                MESSAGE_TITLE, ")
                .append("                MESSAGE_CONTENT, ")
                .append("                TO_CHAR(REC_CRT_TS, 'yyyy-mm-dd hh24:mi:ss') REC_CRT_TS ")
                .append("           FROM  "+ DBConstant.Table.T_APP_MESSAGE_INF)
                .append("          WHERE INS_UUID = ? ")
                .append("            AND REC_ST != '0' ")
                .append("            AND SEND_TYPE = '"+SystemConstant.SEND_TYPE_1+"' ")
                .append("            AND PUBLISH_ST = '"+SystemConstant.PUBLISH_ST+"' ")
                .append("            AND REC_UPD_TS > ? ")
                .append("            and MESSAGE_UUID not in ")
                .append("                (SELECT MESSAGE_UUID ")
                .append("                   FROM  "+ DBConstant.Table.T_APP_CUSTOM_MSG)
                .append("                  WHERE CUSTOM_UUID = ? ")
                .append("                    and READ_ST = '"+SystemConstant.READ_ST_1+"') ")
                .append("          order by REC_UPD_TS desc) A ")
                .append("  where rownum <= 1 ");
        List<Object> params = new ArrayList<>();
        params.add(ins_uuid);
        params.add(custom_crt_ts);
        params.add(custom_uuid);
        List<Map<String,Object>> list = messageInfDao.queryForList(sqlBuf.toString(), params);
        if(list !=null && list.size() > 0 && list.get(0) != null && list.get(0).get("message_uuid") !=null){
            //置该条为已读
            customMsgService.saveMsgStatus(custom_uuid,StringUtils.objToString(list.get(0).get("message_uuid")));
        }
        return list;
    }

    /**
     * 根据会员UUID和发送类型分页得到消息集合
     * @param ins_uuid
     * @param custom_uuid 会员uuid
     * @param send_type
     * @return
     */
    public List<Map<String,String>> getNoticeList(String ins_uuid,String custom_uuid,String send_type, String begin_tm,String end_tm,
                                                  String curr_page,String rows_perpage,Timestamp custom_crt_ts){
        Pagination pagination = new  Pagination();
        pagination.setPage(Integer.parseInt(curr_page));
        pagination.setRows(Integer.parseInt(rows_perpage));
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT A.MESSAGE_UUID AS \"message_uuid\", ")
                .append("        A.MESSAGE_TITLE AS \"message_title\", ")
                .append("        TO_CHAR(A.REC_CRT_TS, 'yyyy-MM-dd HH24:mi:ss') AS \"rec_crt_ts\", ")
                .append("        NVL(B.READ_ST, '0') AS \"read_st\" ")
                .append("   FROM (SELECT MESSAGE_UUID, MESSAGE_TITLE, REC_CRT_TS,REC_UPD_TS ")
                .append("           FROM T_APP_MESSAGE_INF ")
                .append("          WHERE (INS_UUID = ? OR ")
                .append("                CUSTOM_UUID = ?) ")
                .append("            AND REC_ST != '0' ")
                .append("            AND REC_UPD_TS > ? ");
        if(SystemConstant.SEND_TYPE_1.equals(send_type)){//通知公告
            sqlBuf.append("            AND PUBLISH_ST = '"+SystemConstant.PUBLISH_ST+"' ");
        }else if(SystemConstant.SEND_TYPE_2.equals(send_type)){//消息
            sqlBuf.append("            AND MESSAGE_ST = '"+SystemConstant.MESSAGE_ST_1+"' ");
        }else{
            //异常的话不往app显示消息
            sqlBuf.append("            AND 1 = 2 ");
        }
        sqlBuf.append("            AND SEND_TYPE = ?) A ")
                .append("   LEFT JOIN (SELECT DISTINCT MESSAGE_UUID, READ_ST ")
                .append("                FROM T_APP_CUSTOM_MSG ")
                .append("               WHERE CUSTOM_UUID = ?) B ")
                .append("     ON A.MESSAGE_UUID = B.MESSAGE_UUID ")
                .append(" WHERE 1=1 ");

        List<Object> params = new ArrayList();
        params.add(ins_uuid);
        params.add(custom_uuid);
        params.add(custom_crt_ts);
        params.add(send_type);
        params.add(custom_uuid);
        if (!StringUtils.isBlank(begin_tm)) {
            sqlBuf.append("AND A.REC_CRT_TS >= ? ");
            params.add(begin_tm);
        }
        if (!StringUtils.isBlank(end_tm)) {
            sqlBuf.append("AND A.REC_CRT_TS <= ? ");
            params.add(end_tm);
        }
        sqlBuf.append("   ORDER BY A.REC_UPD_TS DESC ");

        pagination.queryString = sqlBuf.toString();
        pagination = messageInfDao.getPagination(pagination, "A", params);
        List<Map<String,String>> resultList =  pagination.getOldData();
        return resultList;
    }

    /**
     * 得到用户所有未读的通知公告uuid集合
     * @param ins_uuid 机构uuid
     * @param custom_uuid 会员uuid
     * @param message_type 消息类型
     * @return
     */
    public List<String> getUnReadNoticeListByCustomUUID(String ins_uuid,String custom_uuid,String message_type,Timestamp custom_crt_ts){
        StringBuffer sqlBuf = new StringBuffer();
        sqlBuf.append(" SELECT MESSAGE_UUID ")
                .append("   FROM  "+Table.T_APP_MESSAGE_INF)
                .append("  WHERE ( INS_UUID = ?  OR CUSTOM_UUID = ? ) ")
                .append("    AND REC_ST != '0' ")
                .append("    AND SEND_TYPE = ? ")
                .append("    AND REC_UPD_TS > ? ");
        if(SystemConstant.SEND_TYPE_1.equals(message_type)){//通知公告
            sqlBuf.append("            AND PUBLISH_ST = '"+SystemConstant.PUBLISH_ST+"' ");
        }else if(SystemConstant.SEND_TYPE_2.equals(message_type)){//消息
            sqlBuf.append("            AND MESSAGE_ST = '"+SystemConstant.MESSAGE_ST_1+"' ");
        }else{
            //例外情况的话不做操作
            sqlBuf.append("            AND 1 = 2 ");
        }
        sqlBuf.append("    and MESSAGE_UUID not in ")
                .append("        (SELECT MESSAGE_UUID ")
                .append("           FROM  "+Table.T_APP_CUSTOM_MSG)
                .append("          WHERE CUSTOM_UUID = ? ")
                .append("            and READ_ST = '1') ");
        List<Object> params = new ArrayList();
        params.add(ins_uuid);
        params.add(custom_uuid);
        params.add(message_type);
        params.add(custom_crt_ts);
        params.add(custom_uuid);
        List<Map<String,Object>> list = messageInfDao.queryForList(sqlBuf.toString(), params);
        if(list != null && list.size()>0){
            List<String> uuids = new ArrayList<>();
            for (Map<String,Object> map : list){
                uuids.add(StringUtils.objToString(map.get("MESSAGE_UUID")));
            }
            return uuids;
        }else{
            return new ArrayList<>();
        }
    }



    /**
     * 通过主键加载消息实体
     * @param message_uuid
     * @return
     */
    public App_Message_InfEntity getNoticeEntityByUUID(String message_uuid){
        return messageInfDao.findByParam("message_uuid",message_uuid);
    }

    /**
     * 记录单个推送记录
     * @param customUuid
     * @param insId
     * @param title
     * @param content
     */
    public void pushMessage(String customUuid, String insId, String title, String content) {
        pushMessage(customUuid, insId, title, content,null);
    }
    
    public void pushMessage(String customUuid, String insId, String title, String content, String operUser){
    	if(StringUtils.isBlank(content) || (StringUtils.isBlank(customUuid) && StringUtils.isBlank(insId))){
    		return;
    	}
    	String appKey = null, masterSecret = null, clientId = null;
    	/*构造推送消息记录*/
        App_Message_InfEntity message = new App_Message_InfEntity();
        message.setMessage_uuid(IDFactoryUtil.getUUID());
        message.setMessage_title(title);
        message.setMessage_content(content);
        message.setMessage_st(SystemConstant.MESSAGE_ST_1);
        message.setRec_crt_ts(new Timestamp(System.currentTimeMillis()));
        message.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
        message.setRec_st(SystemConstant.REC_ST_1);// 正常状态
        message.setLast_oper_in(SystemConstant.OPER_ADD);// 新增记录
        message.setPublish_st(SystemConstant.PUBLISH_ST);// 已发布状态
        message.setSend_type(SystemConstant.SEND_TYPE_2);// 默认发送类型消息推送
        message.setMessage_type(SystemConstant.MESSAGE_TYPE_PRIVATE);// 默认私有消息
    	/*推个人*/
        if (!StringUtils.isBlank(customUuid)) {
    		/*查询出设备类型，会员uuid*/
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT * FROM (SELECT CI.GETUI_CLIENTID,")
            .append("       CI.LOGIN_ID,")
            .append("       CK.APPTYPE,")
            .append("       IA.JG_APPKEY,")
            .append("       IA.JG_MASTERSECRET")
            .append("  FROM ").append(Table.T_APP_CUSTOM_INF).append(" CI")
            .append("  LEFT JOIN ").append(Table.T_APP_LOG_CLIENT_KEY).append(" CK")
            .append("    ON CI.CUSTOM_NO = CK.CUSTOM_NO")
            .append("  LEFT JOIN ").append(Table.T_APP_INS_APP).append(" IA")
            .append("    ON CI.INS_UUID = IA.INS_UUID")
            .append(" WHERE CI.CUSTOM_UUID = ?")
            .append(" ORDER BY CK.REC_UPD_TS DESC) WHERE ROWNUM = 1");
            List<String> param = new ArrayList<>();
            param.add(customUuid);
            List<Map<String, String>> list = messageInfDao.queryForList(sql.toString(), param);
            if (list == null || list.isEmpty()) {
                return;
            }
            Map<String, String> map = list.get(0);
            appKey = map.get("JG_APPKEY");
            masterSecret = map.get("JG_MASTERSECRET");
            clientId = map.get("GETUI_CLIENTID");
            
            message.setCustom_uuid(customUuid);
            message.setRec_upd_usr_id(map.get("LOGIN_ID"));
            message.setMessage_device_tp(map.get("APPTYPE"));// 设备类型
            message.setMessage_term_count("1");//消息发送的设备数
        } else if (!StringUtils.isBlank(insId)) {// 全部推送
            StringBuffer sql = new StringBuffer();
            sql.append("SELECT JG_APPKEY, JG_MASTERSECRET FROM ").append(Table.T_APP_INS_APP).append(" WHERE INS_UUID = ?");
            List<String> param = new ArrayList<>();
            param.add(insId);
            List<Map<String, Object>> list = messageInfDao.queryForList(sql.toString(), param);
            if (list == null || list.isEmpty()) {
                return;
            }
            Map<String, Object> map = list.get(0);
            if (map.get("JG_APPKEY") == null || map.get("JG_MASTERSECRET") == null) {
                return;
            }
            appKey = map.get("JG_APPKEY").toString();
            masterSecret = map.get("JG_MASTERSECRET").toString();
            message.setIns_uuid(insId);
            message.setSend_type(SystemConstant.SEND_TYPE_1);// 发送类型通知公告
            message.setMessage_type(SystemConstant.MESSAGE_TYPE_PUBLIC);// 公有消息
            message.setRec_upd_usr_id(operUser);
        } else {
            return;
        }
    	/*保存记录*/
        messageInfDao.save(message);
    	/*额外内容*/
        Map<String, String> json = new HashMap<>();
        json.put("message_uuid", message.getMessage_uuid());
        json.put("send_type", message.getSend_type());
    	/*开始推送*/
        if (!StringUtils.isBlank(clientId)) {
        	if("1".equals(message.getMessage_device_tp())){
        		jgPushService.pushSingleById(new MposPush(appKey, masterSecret), clientId, title, content, json);
        	}else{
        		jgPushService.pushSingleByAlias(new MposPush(appKey, masterSecret), clientId, title, content, json);
        	}
        } else if (!StringUtils.isBlank(insId)) {
            jgPushService.pushApp(new MposPush(appKey, masterSecret), title, content, json);
        }
    }
    /**
     * 获取会员上下级关系菜单树业务功能
     *
     * @param searchText
     * @return
     */
    public List<Map<String, Object>> getCustomerRelationTree(HttpServletRequest request,String searchText) {
        String ins_phone = String.valueOf(request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_INS_PHONE));
        String sql = "select t1.custom_uuid as ID, t1.sup_custom_uuid as PID, t1.login_id||'-'||t1.name as NAME, (select count(*) from  "
                + Table.T_APP_CUSTOM_INF + " where sup_custom_uuid = t1.custom_uuid) as isParent, t1.getui_clientid as CLIENTID from "
                + Table.T_APP_CUSTOM_INF + " t1 where 1 =1 ";
        List<String> param = new ArrayList<>();
        sql += " and T1.custom_uuid in\n" +
                "       (select tt.custom_uuid\n" +
                "          from T_APP_CUSTOM_INF tt\n" +
                "         start with tt.login_id = "+ins_phone+"\n" +
                "        connect by prior tt.custom_uuid = tt.sup_custom_uuid)\n" +
                "   and T1.rec_st != '0'";
        if(!StringUtils.isBlank(searchText)) {
            sql += " and (login_id like ? or name like ? or custom_no like ? ) ";
            param.add("%" + searchText + "%");
            param.add("%" + searchText + "%");
            param.add("%" + searchText + "%");
        }
        return messageInfDao.queryForList(sql.toString(), param);
    }
}